//
//  TimingSetViewController.m
//  GKBHouse
//
//  Created by hcy on 14-1-15.
//
//

#import "TimingSetViewController.h"
#import "TimeAlarmSetViewController.h"
#import "GKBNavigationBar.h"

@interface TimingSetViewController ()
{
    IBOutlet UITableView *_tableView;
    IBOutlet UIButton *_allCloseButton;
}

@property (retain, nonatomic)NSMutableArray *timeDataArray;
@property (retain, nonatomic)NSMutableArray *weekArray;
@property (assign, nonatomic)NSInteger clearIndex;

@end

@implementation TimingSetViewController

- (void)dealloc
{
    self.timeDataArray = nil;
    self.weekArray = nil;
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    [self initTopBar];
    [self initLabel];
    
//    [_tableView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"sceneTableBack.png"]]];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:_tableView.frame];
    [imageView setImage:[UIImage imageNamed:@"sceneTableBack.png"]];
    [_tableView setBackgroundView:imageView];
    [imageView release];
    
    [[_tableView layer]setCornerRadius:9];
    [[_tableView layer]setMasksToBounds:YES];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    self.weekArray = [NSMutableArray array];
    
//    self.weekArray = @[NSLocalizedString(@"Mon", nil), NSLocalizedString(@"Tue", nil), NSLocalizedString(@"Wed", nil), NSLocalizedString(@"Thurs", nil), NSLocalizedString(@"Friday", nil), NSLocalizedString(@"Sat", nil), NSLocalizedString(@"Sun", nil)];
    
     NSArray *titleArray = @[@"Mon", @"Tue", @"Wed", @"Thurs", @"Friday", @"Sat", @"Sun"];
    
    for (NSString *title in titleArray) {
        [self.weekArray addObject:NSLocalizedString(title, nil)];
    }
    
    [self getTimeData];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
//}


#pragma mark - init

- (void)initTopBar
{
    GKBNavigationBar *topBar = [[GKBNavigationBar alloc]init];
    [topBar setTarget:self returnAction:@selector(dismissView) withTitle:NSLocalizedString(@"timingSet", nil)];
    [self.view addSubview:topBar];
    [topBar release];
    
}

- (void)dismissView
{
    [self dismissModalViewControllerAnimated:NO];
}

- (void)initLabel
{
//    [nameLabel setText:NSLocalizedString(@"sceneName", nil)];
//    [okButton setTitle:NSLocalizedString(@"ok", nil) forState:UIControlStateNormal];
//    
//    [nameText setText:self.sceneName];
//    nameText.delegate = self;
    
    //  [nameText addTarget:self action: @selector(changePhoneNumValue) forControlEvents:UIControlEventEditingChanged];//手机号码
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kTimingSetCellHeight;
}

#pragma mark - UITableViewDataSourceDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.timeDataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifyCell = @"TimingSetCell";
    TimingSetCell *cell = (TimingSetCell*)[tableView dequeueReusableCellWithIdentifier:identifyCell];
    if (cell == nil) {
        cell = [[[TimingSetCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifyCell]autorelease];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    }
    
    cell.delegate = self;
    cell.indexPath = indexPath;
    
    NSDictionary *dic = [self.timeDataArray objectAtIndex:indexPath.row];
    
    //定时状态：是否开启:1: 表示开启 0: 表示关闭
    NSNumber *time_state = [dic objectForKey:@"time_state"];
    
    if (time_state != nil) {
        
        [cell.onOffBtn setEnabled:YES];
        [cell.clearBtn setEnabled:YES];
        
        if (time_state.intValue == 1) {
            [cell.onOffBtn setSelected:YES];
        }
        if (time_state.intValue == 0) {
            [cell.onOffBtn setSelected:NO];
        }
    }
    else//未设置数据
    {
        [cell.onOffBtn setEnabled:NO];
        [cell.clearBtn setEnabled:NO];
    }
    
    
    //时间
    NSNumber *hour = [dic objectForKey:@"d10_time1"];
    NSNumber *minute = [dic objectForKey:@"d11_time2"];
    NSNumber *onOff = [dic objectForKey:@"d8_orderId"];
    
    // 1表示 定时开; 2 表示 定时关
    NSString *timeOnOff = @"";
    if (onOff.intValue == 1) {
        timeOnOff = NSLocalizedString(@"Timing-ON", nil);
    }
    if (onOff.intValue == 2) {
        timeOnOff = NSLocalizedString(@"Timing-OFF", nil);
    }
    
    NSString *timeString = [NSString stringWithFormat:@"%02d:%02d(%@)", hour.integerValue, minute.integerValue, timeOnOff];
    [cell.timeLabel setText:timeString];
    
    if (hour == nil) {//未设置数据
        cell.timeLabel.text = @"";
    }
    
    //星期
    NSString *weekIds = [dic objectForKey:@"d9_mode"];
 
    cell.weekLabel.text = [self weeks:weekIds];
    //电器
    NSString *switchStr = [dic objectForKey:@"switchStr"];
    
    cell.wiringLabel.text = [TimingSetViewController wirings:switchStr];
    
    
    return cell;
}

- (NSString *)weeks:(NSString *)weekIds
{
    //"0" 表示一次
    if (weekIds != nil && [weekIds isEqualToString:@"0"]) {
        return NSLocalizedString(@"Timing-once", nil);
    }
    
    NSArray *days = [weekIds componentsSeparatedByString:@","];
    
    NSString *weekString = @"";

    
    if ([days count] == 7 && ![days containsObject:@""]) {
        weekString = NSLocalizedString(@"Timing-everyday", nil);
        return weekString;
    }
    
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSString *day in days) {
        NSInteger d = day.integerValue;
        
        if (d>0 && d<8) {
            NSString *weekIndex = [self.weekArray objectAtIndex:d - 1];
            [array addObject:weekIndex];
        }
    }
    
    weekString = [array componentsJoinedByString:@","];
    
    return weekString;
}

+ (NSString *)wirings:(NSString *)switchStr
{
    NSArray *switchIdArray = [switchStr componentsSeparatedByString:@","];
    NSMutableArray *switchNameArray = [NSMutableArray array];
    
    for (NSString *switchId in switchIdArray) {
        if ([switchId length]>0) {
            NSString *switchName = [TimingSetViewController getSwitchName:switchId];
            if ([switchName length]>0) {
                [switchNameArray addObject:switchName];
            }
        }
    }
    
    NSString *names = [switchNameArray componentsJoinedByString:@","];
    
    return names;
}

+ (NSString *)getSwitchName:(NSString *)switchId
{
    GKBMainController *mainController = [GKBMainController mainCtr];
    NSArray *equipmentArray = mainController.equipments;

    NSString *switchName = @"";
    
    for (NSDictionary *switchItem in equipmentArray) {
        NSString *switchItemId = [switchItem objectForKey:@"switchId"];
        if ([switchId isEqualToString:switchItemId]) {
            NSString *tagName = [switchItem objectForKey:@"tagName"];
            NSString *name = [switchItem objectForKey:@"name"];
            
            switchName = [tagName stringByAppendingString:name];
            
            break;
        }
    }
    
    return switchName;
    
}


#pragma mark - TimingSetCellDelegate

- (void)TimingSetCell:(TimingSetCell *)cell OnOff:(BOOL)state
{
    NSDictionary *dic = [self.timeDataArray objectAtIndex:cell.indexPath.row];
    NSString *groupNum = [dic objectForKey:@"groupNo"];
    
    NSString *ctlId = @"";
    
    if (state == YES) {//已开启，将它关
        ctlId = @"2";
    }
    if (state == NO) {//已关闭，将它开
        ctlId = @"1";
    }
    
    [self startTime:ctlId groupNum:groupNum];
}

- (void)TimingSetCellSetting:(TimingSetCell *)cell
{
    NSMutableDictionary *dic = [self.timeDataArray objectAtIndex:cell.indexPath.row];
    if ([dic count] == 0) {
        [dic setObject:[NSNumber numberWithInteger:cell.indexPath.row + 1] forKey:@"groupNo"];
    }
    TimeAlarmSetViewController *vc = [[TimeAlarmSetViewController alloc]initWithTimingDic:dic saveTarget:self action:@selector(settingSaveSuccess)];
    [self presentModalViewController:vc animated:NO];
    [vc release];
}

- (void)TimingSetCellClear:(TimingSetCell *)cell
{
    NSDictionary *dic = [self.timeDataArray objectAtIndex:cell.indexPath.row];
    NSNumber *groupNum = [dic objectForKey:@"groupNo"];
    
    self.clearIndex = groupNum.integerValue - 1;
    
    [self delTimeGroupNum:groupNum];
}


#pragma mark - action

- (BOOL)isAllStop
{
    //是否全部已关闭
    for (NSMutableDictionary *dic in self.timeDataArray) {
        
        NSNumber *state = [dic objectForKey:@"time_state"];
        
        if (state && state.integerValue == 1) {//如果有一个开的，就不是全关
            return NO;
        }
    }
    return YES;
}

- (void)updateAllStopButton
{
    BOOL isAllStop = [self isAllStop];//是否全部已关闭
    
    if (isAllStop) {
        [_allCloseButton setBackgroundImage:[UIImage imageNamed:@"redNormal.png"] forState:UIControlStateNormal];
        [_allCloseButton setBackgroundImage:[UIImage imageNamed:@"redSelect.png"] forState:UIControlStateHighlighted];
    }
    else
    {
        [_allCloseButton setBackgroundImage:[UIImage imageNamed:@"green_normal.png"] forState:UIControlStateNormal];
        [_allCloseButton setBackgroundImage:[UIImage imageNamed:@"green_click.png"] forState:UIControlStateHighlighted];
    }
}

- (IBAction)stopAllTimeAction
{
    BOOL isAllStop = [self isAllStop];//是否全部已关闭
    //所有定时为关
    if (isAllStop) {
        NSString *tip = NSLocalizedString(@"Timing-none-open", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
    }
    else{//有定时为开，执行全关
        [self stopAllTime];
    }
    
    
}

- (void)settingSaveSuccess
{
    [_tableView reloadData];
    [self updateAllStopButton];
}
#pragma mark - 网络

//读取主机的全部定时数据
- (void)getTimeData
{
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    
    NSString *tip = NSLocalizedString(@"Timing-getTimeData", nil);
    [iToast showTip:tip gravity:iToastGravityBottom];
    
    NSString *errorTip = NSLocalizedString(@"Timing-getTimeData-error", nil);
    [WebServices setShowConnectting:YES];
    [WebServices requestStartOrder:@"getTimeData" body:body target:self action:@selector(getTimeDataEnd:) errorTip:errorTip];
    
//    [self getTimeDataEnd:nil];
}

- (void)getTimeDataEnd:(NSDictionary *)dic
{
    [WebServices setShowConnectting:NO];//关闭提示

    if (TARGET_IPHONE_SIMULATOR) {
        if (dic == nil) {
            dic = [self testDic];
        }
    }
    
    NSNumber *result = [dic objectForKey:@"result"];
    NSArray *timeData = [dic objectForKey:@"timeData"];
    if (result.integerValue == 0 && result != nil) {
//        [self setRoomsState:states];
        [self setTimeData:timeData];
        [self updateAllStopButton];
    }
    else
    {
        NSString *tip = NSLocalizedString(@"Timing-getTimeData-error", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
        
    }
    
}

- (void)setTimeData:(NSArray *)timeData
{
    NSMutableArray *array = [NSMutableArray array];
    
    for (int i = 0; i<10; i++) {
        [array addObject:[NSMutableDictionary dictionary]];
    }
    
    for (NSDictionary *dic in timeData) {
        NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        NSNumber *gourpNo = [muDic objectForKey:@"groupNo"];
        
        [array replaceObjectAtIndex:gourpNo.integerValue - 1 withObject:muDic];
    }
    self.timeDataArray = array;
    [_tableView reloadData];
    
}

- (NSDictionary *)testDic
{
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"TestTimeData" ofType:@""];
    NSString *string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    
    NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    NSDictionary *dic = [jsonObject objectAtIndex:0];
    
    return dic;
}

//全关
- (void)stopAllTime
{
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    
    NSString *tip = NSLocalizedString(@"Timing-stopAllTime", nil);
    [iToast showTip:tip gravity:iToastGravityBottom];
    
    NSString *errorTip = NSLocalizedString(@"Timing-stopAllTime-error", nil);
//    [WebServices setShowConnectting:YES];
    [WebServices requestStartOrder:@"stopAllTime" body:body target:self action:@selector(stopAllTimeEnd:) errorTip:errorTip];
}

- (void)stopAllTimeEnd:(NSDictionary *)dic
{
    [WebServices setShowConnectting:NO];//关闭提示
    
    NSNumber *result = [dic objectForKey:@"result"];
    
    if (result.integerValue == 0 && result != nil) {
        NSString *tip = NSLocalizedString(@"operat success!", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
        
        [self stopAllTimingSetting];
        [self updateAllStopButton];
    }
    else
    {
        NSString *tip = NSLocalizedString(@"Timing-stopAllTime-error", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
    }
    
}

- (void)stopAllTimingSetting
{
    for (NSMutableDictionary *dic in self.timeDataArray) {
        if ([dic objectForKey:@"time_state"] != nil) {
            [dic setObject:[NSNumber numberWithInt:0] forKey:@"time_state"];
        }
    }
    
    [_tableView reloadData];
}

//开启/停止各组的定时任务
- (void)startTime:(NSString *)ctlId groupNum:(NSString *)groupNum
{
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\",\"groupNum\":\"%@\",\"ctlId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId, groupNum, ctlId];
    
    NSString *tip = @"";

    if ([ctlId isEqualToString:@"1"]) {
        tip = NSLocalizedString(@"opening", nil);
    }
    if ([ctlId isEqualToString:@"2"]) {
        tip = NSLocalizedString(@"closing", nil);
    }
    
     NSLog(@"startTimeBody:%@", body);
    
    [iToast showTip:tip gravity:iToastGravityBottom];
    
    NSString *errorTip = NSLocalizedString(@"operatFailure", nil);
    [WebServices requestStartOrder:@"startTime" body:body target:self action:@selector(startTimeEnd:) errorTip:errorTip];
    
}

- (void)startTimeEnd:(NSDictionary *)dic
{
    [WebServices setShowConnectting:NO];//关闭提示
    
    NSNumber *result = [dic objectForKey:@"result"];
    
    if (result.integerValue == 0 && result != nil) {
        NSString *tip = NSLocalizedString(@"operat success!", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
        [self updateGroupNoState:dic];
        [self updateAllStopButton];
    }
    else
    {
        NSString *tip = NSLocalizedString(@"operatFailure", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
    }
}

- (void)updateGroupNoState:(NSDictionary *)dic
{
    NSArray *groupNoArray = [dic objectForKey:@"stateGroup"];
    
    for (NSDictionary *groupDic in groupNoArray) {
        NSNumber *groupNo = [groupDic objectForKey:@"groupNo"];
        NSNumber *state = [groupDic objectForKey:@"state"];
        
        for (NSDictionary *group in self.timeDataArray) {
            
            NSNumber *groupId = [group objectForKey:@"groupNo"];
            if (groupNo != nil && groupId != nil && [groupNo isEqualToNumber:groupId]) {
                if ([group objectForKey:@"time_state"] != nil) {
                    [group setValue:state forKey:@"time_state"];
                }
            }
        }
    }
    
    [_tableView reloadData];
}

//删除定时数据
- (void)delTimeGroupNum:(NSNumber *)groupNum
{
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\",\"groupNum\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId, groupNum];
    
    NSString *tip = NSLocalizedString(@"Timing-delTime", nil);;
    
    
    [iToast showTip:tip gravity:iToastGravityBottom];
    
    NSString *errorTip = NSLocalizedString(@"operatFailure", nil);
    [WebServices requestStartOrder:@"delTime" body:body target:self action:@selector(delTimeEnd:) errorTip:errorTip];
    
}

- (void)delTimeEnd:(NSDictionary *)dic
{
    [WebServices setShowConnectting:NO];//关闭提示
    
    NSNumber *result = [dic objectForKey:@"result"];
    
    if (result.integerValue == 0 && result != nil) {
        NSString *tip = NSLocalizedString(@"operat success!", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
        
        //成功清除，设置空数据
        [self.timeDataArray replaceObjectAtIndex:self.clearIndex withObject:[NSMutableDictionary dictionary]];
        [_tableView reloadData];
        [self updateAllStopButton];
    }
    else
    {
        NSString *tip = NSLocalizedString(@"operatFailure", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
    }
}

@end
